package per.hnvcam.searchext.controller;

import org.apache.log4j.Logger;
import org.apache.tika.exception.TikaException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.xml.sax.SAXException;
import per.hnvcam.searchext.Constants;
import per.hnvcam.searchext.data.model.SearchInformation;
import per.hnvcam.searchext.data.model.SystemConfiguration;
import per.hnvcam.searchext.services.ClassificationService;
import per.hnvcam.searchext.services.SpecialQuery;
import per.hnvcam.thread.MultiTaskManager;
import per.hnvcam.thread.Task;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Vi Cam
 * Date: 10/01/2012
 * Time: 22:50
 * To change this template use File | Settings | File Templates.
 */
@Controller("SearchController")
public class SearchController {
   private static Logger LOG = Logger.getLogger(SearchController.class);

   @Autowired
   @Qualifier("ClassificationService")
   private ClassificationService classificationService;

   @Autowired
   @Qualifier("SpecialQuery")
   private SpecialQuery specialQuery;

   private static final String HOME_PAGE = "home";
   private static final String SEARCH_RESULT_PAGE = "result";

   @RequestMapping(value = "/index.jhtml", method = RequestMethod.GET)
   public String showMainSearchPage(HttpServletRequest request, Model model) {
      SystemConfiguration systemConfiguration = specialQuery.getSystemConfiguration();
      model.addAttribute("classTypes", systemConfiguration.getClasses());
      model.addAttribute("searchInfo", new SearchInformation());
      return HOME_PAGE;
   }

   @RequestMapping(value = "/index.jhtml", method = RequestMethod.POST)
   public String doSearch(HttpServletRequest request, Model model,
                          @ModelAttribute(value = "searchInfo") SearchInformation searchInformation) throws IOException, SAXException, TikaException {
      final Map<String, String> searchResult = classificationService.searchGoogleFor(searchInformation.getSearchText());
      final Map<String, String> linkList = new HashMap<String, String>();
      final Map<String, List<String>> linkClassNames = new HashMap<String, List<String>>();
      final String filterType = searchInformation.getFilterClass();
      MultiTaskManager multiTaskManager = MultiTaskManager.getDefaultInstance();
      for (String link : searchResult.keySet()) {
         final String url = link;
         multiTaskManager.addTask(new Task(new Runnable() {
            @Override
            public void run() {
               long startTime = new Date().getTime();
               LOG.info("Classifying " + url);
               List<String> classifiedClasses = null;
               try {
                  classifiedClasses = classificationService.classify(new URL(url));
               } catch (Exception e) {
                  e.printStackTrace();
               }
               if (filterType.equals(Constants.FILTER_NONE) || classifiedClasses.contains(filterType)) {
                  linkList.put(url, searchResult.get(url));
                  List<String> classNames = new ArrayList<String>();
                  if (classifiedClasses.size() > 0) {
                     for (String classifiedClass : classifiedClasses) {
                        classNames.add(classificationService.getTypeName(classifiedClass));
                     }
                  } else {
                     classNames.add(Constants.UNCLASSIFIED_CLASS);
                  }

                  linkClassNames.put(url, classNames);
               }
               long duration = new Date().getTime() - startTime;
               LOG.info("Done in " + duration + "ms.");
            }
         }));
      }
      while (multiTaskManager.getThreadCount() > 0) {
         //LOG.info(multiTaskManager.getThreadCount());
         try {
            Thread.sleep(1000);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
      SystemConfiguration systemConfiguration = specialQuery.getSystemConfiguration();
      model.addAttribute("classTypes", systemConfiguration.getClasses());
      model.addAttribute("searchInfo", new SearchInformation());
      model.addAttribute("linkList", linkList);
      model.addAttribute("linkClassNames", linkClassNames);
      return SEARCH_RESULT_PAGE;
   }
}
